﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).
using System;

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        /// <summary>
        ///     Bulk delete.
        /// </summary>
        /// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
        public void BulkDelete()
        {
            PreLogicSetting();

            if (!HasRow()) return;

            if (IsBulkStategy())
            {
                SetCommonSettingBulk();

                EnsureTransactionIsSet();

                if (!IsValid()) return;

                SetInternalDataSourceBulk();
                AddCustomSetting();

                SetSqlDeleteActionBulk();
                SetSqlDropTemporaryTable();

                try
                {
                    CreateTemporaryTable();
                    WriteToServer();
                    ExecuteBulkAction();
                    DropTemporaryTable();

                    if (IsInternalTransaction)
                    {
                        SqlTransaction.Commit();
                    }
                }
                catch (Exception)
                {
                    if (IsInternalTransaction)
                    {
                        SqlTransaction.Rollback();
                    }
                    throw;
                }
                finally
                {
                    RemoveCustomSetting();
                }
            }
            else
            {
                SetCommonSettingSingle();

                if (!IsValid()) return;

                SetInternalDataSourceSingle();
                SetSqlDeleteActionSingle();
                ExecuteActionSingle();
            }
        }
    }
}